package com.lkyh.pad;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;


public class MainActivity extends Activity {
    public final static String APP_TYPE = "mes";
    public final static String ACCOUNT_FILE_NAME = "pda_account.txt";
    private final static int SCANNIN_GREQUEST_CODE = 1;
    //记录用户首次点击返回键的时间
    private long firstTime = 0;
    private WebView web;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
        initView();
    }

    private void initView() {

        web = findViewById(R.id.web);
        web.getSettings().setJavaScriptEnabled(true);
        web.addJavascriptInterface(this, "pda");
        web.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                view.getSettings().setJavaScriptEnabled(true);
                super.onPageFinished(view, url);
            }

        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            web.getSettings().setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        web.getSettings().setUseWideViewPort(true); //将图片调整到适合webview的大小
        web.getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        web.getSettings().setLoadsImagesAutomatically(true); //支持自动加载图片
        String url = FileUtil.getFile(SettingActivity.FILE_NAME);
        if (null == url || "".equals(url)) {
            url = SettingActivity.DEFAULT_URL;
        }
        url += "?appType=" + APP_TYPE;
        web.loadUrl(url);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Toast.makeText(MainActivity.this, web.getUrl(), Toast.LENGTH_SHORT).show();
        if (keyCode == KeyEvent.KEYCODE_BACK && web.canGoBack() && !web.getUrl().endsWith("index") && !web.getUrl().endsWith("login")) {
            web.goBack();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出APP", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                finish();
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {

                    //显示扫描到的内容
                    String result = data.getStringExtra("result").trim();
//                    Toast.makeText(MainActivity.this,"扫描的结果:"+result,Toast.LENGTH_LONG).show();
                    //更新webView内容

                    web.loadUrl("javascript:scanReturn('" + result + "')");

                }
                break;
        }
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 333);
                return;
            } else {

            }
        } else {

        }
    }

    @android.webkit.JavascriptInterface
    public void scan() {
        runOnUiThread(() -> {
            Intent intent = new Intent();
            intent.setClass(MainActivity.this, MipcaActivityCapture.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivityForResult(intent, SCANNIN_GREQUEST_CODE);

        });
    }

    @android.webkit.JavascriptInterface
    public void rememberMe(String json) {
        FileUtil.saveFile(json, ACCOUNT_FILE_NAME);
    }

    @android.webkit.JavascriptInterface
    public String getRemember() {
        return FileUtil.getFile(ACCOUNT_FILE_NAME);
    }

    @android.webkit.JavascriptInterface
    public void notRememberMe() {
        FileUtil.deletefile(ACCOUNT_FILE_NAME);
    }

    @android.webkit.JavascriptInterface
    public void saveImage() {
        saveImageToGallery(MainActivity.this, BitmapFactory.decodeResource(getResources(), R.drawable.us));
        Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "pda");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + appDir.getAbsolutePath())));

    }


    /*//供js调用的接口
    @android.webkit.JavascriptInterface
    public Object toAndroid(String functionName, String json) {
        Class<? extends MainActivity> aClass = this.getClass();
        try {
            if (null == json || "".equals(json)) {
                return aClass.getMethod(functionName).invoke(this);
            } else {
                return aClass.getMethod(functionName, JSONObject.class).invoke(this, JSONObject.parseObject(json)
                );
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    @android.webkit.JavascriptInterface
    public Object toAndroid(String functionName) {
        Class<? extends MainActivity> aClass = this.getClass();
        try {
            return aClass.getMethod(functionName).invoke(this);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }*/

}
